import request from "@/axios";
import { defineStore } from "pinia";
import { store } from "./store";
import { useStorage } from "@/hooks/useStorage";
import { computed, ref, toRaw } from "vue";

const TokenKey = "mtrworkflow_token";
const ThirdpartTokenKey = "Thirdpart_mtrworkflow_token";
const UserKey = "mtrworkflow_user";
const AppIdKey = "mtrworkflow_appid";

const storage = useStorage("localStorage");

export const useAppUserStore = defineStore("AppUser", () => {
  const token = ref("");
  token.value = getToken();

  const currentUser = ref({});
  currentUser.value = getCurrentUser();

  const thirdpartToken = ref("");
  thirdpartToken.value = getThirdpartToken();

  const appid = ref();

  function setToken(_token) {
    token.value = _token;
    return storage.setStorage(TokenKey, _token);
  }
  function getToken() {
    return storage.getStorage(TokenKey);
  }
  function setAppId(_appid) {
    appid.value = _appid;
    return storage.setStorage(AppIdKey, _token);
  }
  function getAppId() {
    return storage.getStorage(AppIdKey);
  }
  function removeToken() {
    token.value = "";
    currentUser.value={};
    thirdpartToken.value = "";
    storage.setStorage(UserKey,"");
    storage.setStorage(ThirdpartTokenKey, "");
    return storage.removeStorage(TokenKey);
  }
  function setCurrentUser(user,isReplace) {
    if (!user.isManager &&!isReplace) {
      currentUser.value.id = user.id;
      currentUser.value.name = user.name;
    } else {
      currentUser.value = user;
    }

    return storage.setStorage(UserKey, toRaw(currentUser.value));
  }
  function getCurrentUser() {
    try {
      return storage.getStorage(UserKey);
    } catch (e) {
      return {};
    }
  }

  function getThirdpartToken() {
    return storage.getStorage(ThirdpartTokenKey);
  }
  function setThirdpartToken(token) {
    thirdpartToken.value = token;
    return storage.setStorage(ThirdpartTokenKey, token);
  }

  return {
    token,
    currentUser,
    thirdpartToken,
    setToken,
    getToken,
    setAppId,
    getAppId,
    removeToken,
    setCurrentUser,
    getCurrentUser,
    setThirdpartToken,
    getThirdpartToken,
  };
});

export const useAppUserStoreWithOut = () => {
  return useAppUserStore(store);
};
